/* eslint-disable max-lines-per-function */
import React, {useState, useRef} from 'react';
import ProTable, {ProColumns, ActionType} from '@ant-design/pro-table';
import {Button, Space, notification, Popconfirm} from 'antd';
// @ts-ignore
import {useRequest} from 'umi';
import {useCreation, useBoolean, usePersistFn} from 'ahooks';
import {getList, getVarietys, saveItem, delItem} from './service';
import EditForm, {ADD_TYPE, EDIT_TYPE} from './EditForm';

const iconStyle = {
    padding: 0
};


export default () => {

    const [formVisible, {setTrue, setFalse}] = useBoolean(false);
    const [formType, setType] = useState<string>(ADD_TYPE);
    const [curCat, setCurCat] = useState<API.CatItem>(null);

    const actionRef = useRef<ActionType>();

    // 枚举值接口
    const {data: varietyEnum} = useRequest(getVarietys, {
        formatResult(res) {
            const {data} = res || {};
            const {list = []} = data || {};
            return list?.reduce((total, cur) => {
                total[cur.key] = {text: cur.label};
                return total;
            }, {});
        }
    });

    // 保存接口
    const {run: handleSave} = useRequest(saveItem, {
        manual: true,
        onSuccess() {
            notification.success({message: '保存成功'});
            actionRef.current.reload();
        }
    });

    // 删除接口
    const {run: handleDel} = useRequest(delItem, {
        manual: true,
        onSuccess() {
            notification.success({message: '删除成功'});
            actionRef.current.reload();
        }
    });

    // 添加按钮点击事件
    const handleAdd = usePersistFn(() => {
        setTrue();
        setType(ADD_TYPE);
    });

    // 编辑按钮点击事件
    const handleEdit = usePersistFn((record: API.CatItem) => {
        setTrue();
        setType(EDIT_TYPE);
        setCurCat(record);
    });

    // 表格列
    const columns: ProColumns<API.CatItem>[] = useCreation(() => [
        {
            title: '猫名',
            dataIndex: 'name',
            ellipsis: true,
        },
        {
            title: '猫龄',
            dataIndex: 'age',
            search: false,
            sorter: true,
        },
        {
            title: '品种',
            dataIndex: 'variety',
            valueEnum: varietyEnum
        },
        {
            title: '出生日期',
            dataIndex: 'birthday',
            valueType: 'date',
            search: false,
        },
        {
            title: '操作',
            valueType: 'option',
            render: (_, record) => (
                <Space size={10}>
                    <Button type="link" style={iconStyle} onClick={() => handleEdit(record)}>编辑</Button>
                    <Popconfirm title="确定删除么？" onConfirm={() => handleDel(record?.id)}>
                        <Button type="link" style={iconStyle}>删除</Button>
                    </Popconfirm>
                </Space>
            )
        },
    ], [varietyEnum]);

    // 保存
    const handelSave = usePersistFn(values => {
        handleSave(values);
        setFalse();
        return Promise.resolve(true);
    });

    return (
        <>
            <ProTable<API.CatItem>
                columns={columns}
                actionRef={actionRef}
                request={getList}
                rowKey="id"
                search={{labelWidth: 'auto'}}
                pagination={{pageSize: 10}}
                dateFormatter="string"
                // eslint-disable-next-line react/jsx-no-bind
                toolBarRender={() => [
                    <Button key="button" type="primary" onClick={handleAdd}>
                        新建
                    </Button>
                ]}
            />
            <EditForm
                varietyEnum={varietyEnum}
                visible={formVisible}
                onCancel={setFalse}
                onFinish={handelSave}
                type={formType}
                initialValues={curCat}
            />
        </>
    );
};
